import numpy as np
import matplotlib.pyplot as plt
import numpy.fft as fft

####
import numpy as np
import matplotlib.pyplot as plt
import numpy.fft as fft
import time

def triangle(t,W):
    if(t>1)|(t<-1):
        return 0
    elif(-1<=t<0):
        return 1/W*t+1
    elif(0<=t<1):
        return -1/W*t+1

n=1000

x = np.linspace(-2, 2, n)

y = np.zeros(x.size)

for i in range(n):
    y[i]=triangle(x[i],1)
##print(x,y)

complex_array = fft.fft(y)
##print(complex_array.shape)  # (1000,) 
##print(complex_array.dtype)  # complex128 
##print(complex_array[0])  # (-2.1458390619955026e-12+0j)
y_new = fft.ifft(complex_array)

freqs = fft.fftfreq(x.size, x[1] - x[0])
# 复数的模为信号的振幅（能量大小）
complex_array = fft.fft(y)
pows = np.abs(complex_array)

####



plt.subplot(311)# 必须先指定子图才能使用！
plt.grid(linestyle=':')
plt.plot(x, y, label='y')  # y是1000个相加后的正弦序列
plt.subplot(312)
plt.plot(x, y_new, label='y_new', color='orangered')  # y是ifft变换后的序列
plt.grid(linestyle=':')
# 得到分解波的频率序列


plt.subplot(313)
plt.title('Frequency Domain', fontsize=16)
plt.xlabel('Frequency', fontsize=12)
plt.ylabel('Power', fontsize=12)
plt.grid(linestyle=':')
plt.plot(freqs, pows, c='orangered', label='Frequency')
plt.legend()

